package com.framework.module_google

import android.accounts.Account
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.api.client.extensions.android.http.AndroidHttp
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.drive.Drive
import com.google.api.services.drive.DriveScopes
import org.json.JSONArray
import org.json.JSONObject
import java.util.Collections


/**
 * @author: HeXinGen
 * @date: 2024/1/3
 * @descption:
 *
 * 1.谷歌登录(邮箱)
 * 2.谷歌Drive(云盘)
 */
object GoogleApi {


    @Volatile
    var driveServiceHelper: DriveServiceHelper? = null

    var googleLogin = GoogleLogin()


    /**
     * 测试谷歌授权登录，根据后台申请的客户端凭证
     */
    fun authorizedLoginAndroidX(
        appCompatActivity: AppCompatActivity,
        callback: GoogleApiListener<GoogleSignInAccount>
    ) {
        googleLogin.authorizedLoginAndroidx(appCompatActivity,
            object : GoogleLogin.GoogleSignListener {
                override fun success(googleSignInAccount: GoogleSignInAccount) {
                    // success log 打印：Signed in as  , h13767004362@gmail.com
                    printI(" Signed in as ${googleSignInAccount.email}")
                    /*   googleSignInAccount.email?.run {
                           initDriveByGoogleAccount(appCompatActivity,this)
                       }*/
                    callback.success(googleSignInAccount)
                }

                override fun error(error: Exception) {
                    printException("google login fair", error)
                    callback.error(error)
                }

            })
    }

    fun authorizedLogin(activity: Activity) {
        googleLogin.authorizedLogin(activity)
    }

    fun handleAuthorizedLoginIntent(
        requestCode: Int,
        resultCode: Int,
        intent: Intent?,
        callback: GoogleApiListener<GoogleSignInAccount>
    ) {
        googleLogin.handleGoogleSignIntent(requestCode, resultCode, intent, object :
            GoogleLogin.GoogleSignListener {
            override fun success(googleSignInAccount: GoogleSignInAccount) {
                callback.success(googleSignInAccount)
            }

            override fun error(error: Exception) {
                callback.error(error)
            }
        })
    }

    /**
     *
     * 调用谷歌授权登录,且指定访问drive的空间权限。
     */
    fun startGoogleSingAndDriveAndroidx(appCompatActivity: AppCompatActivity) {

        googleLogin.loginGoogleEmailAndGoogleDrive(appCompatActivity,
            object : GoogleLogin.GoogleSignListener {
                override fun success(googleSignInAccount: GoogleSignInAccount) {
                    // success log 打印：Signed in as  , h13767004362@gmail.com
                    printI(" Signed in as ${googleSignInAccount.email}")
                    //根据谷歌账户的信息，创建对应的drive对象，进行云盘存储功能。
                    initDriveByGoogleAccount(appCompatActivity, googleSignInAccount.account)
                }

                override fun error(error: Exception) {
                    printException("google login  fair", error)
                }

            })
    }

    /**
     * 外部传入谷歌邮箱，来操作云盘Drive对象。
     */
    fun initDriveByGoogleAccount(activity: Context, email: String) {
        initDriveByGoogleAccount(activity, Account(email, "com.google"))
    }

    /**
     * 查询drive的云盘文件中列表
     */
    fun queryFileList(regex: String, callback: GoogleApiListener<JSONArray>) {

        driveServiceHelper?.queryFiles()?.let {
            it.addOnSuccessListener {
                val fileList = it.files
                val array = JSONArray()
                for (i in fileList) {
                    val match = i.name.contains(regex)
                    if (match) {
                        //匹配指定的文件名
                        array.put(JSONObject().apply {
                            this.put("fileId", i.id)
                            this.put("fileName", i.name)
                            this.put("fileOriginName", i.originalFilename)
                        })
                        printI("query file list:${i.name}")
                    }
                }
                callback.success(array)
            }
            it.addOnFailureListener {
                callback.error(it)
            }
        }
    }

    /**
     * 从谷歌云盘中下载文件
     */
    fun downloadFileFromDrive(fileId: String, callback: GoogleApiListener<String>) {
        driveServiceHelper?.readFile(fileId)?.let {
            it.addOnSuccessListener {
                //下载
                callback.success(it.second)
            }
            it.addOnFailureListener {
                //下载失败
                callback.error(it)
            }
        }
    }

    /**
     * 根据谷歌邮箱账号,来创建云盘drive操作对象。
     */
    private fun initDriveByGoogleAccount(activity: Context, account: Account?) {
        if (driveServiceHelper == null) {
            LogUtils.printI("initDriveByGoogleAccount()")
            val credential = GoogleAccountCredential.usingOAuth2(
                activity,
                Collections.singleton(DriveScopes.DRIVE_FILE)
            ).apply {
                this.selectedAccount = account
            }
            val googleDrive =
                Drive.Builder(AndroidHttp.newCompatibleTransport(), GsonFactory(), credential)
                    .build()
            driveServiceHelper = DriveServiceHelper(googleDrive)
        }

        //  testUploadFile()
    }

    /**
     * 先创建file Id， 通过它来更新内容
     */
    fun testUploadFile() {
        driveServiceHelper?.createFile()?.run {
            this.addOnSuccessListener {
                var fileId = it
                printI("create drive file success $fileId")
                // testSaveTask(fileId)
            }
            this.addOnFailureListener {
                printException("create drive file fair", it)
            }
        }
    }

    val TAG = "GoogleApi"

    /**
     * 打印异常的调用栈
     * @param msg
     * @param throwable
     */
    fun printException(msg: String?, throwable: Throwable?) {
        Log.e(TAG, msg, throwable)
    }

    fun printI(msg: String) {
        Log.e(TAG, msg)
    }

    fun uploadFileToGoogleDrive(filePath: String, callback: GoogleApiListener<String>) {
        driveServiceHelper?.uploadFile(filePath)?.let {
            it.addOnSuccessListener {
                //上传成功
                callback.success(it)
            }
            it.addOnFailureListener {
                //上传失败
                callback.error(it)
            }
        }
    }

    fun testSaveTask(fileId: String) {
        driveServiceHelper?.saveFile(
            fileId,
            "test_temp_${System.currentTimeMillis()}",
            "this is goggle drive_test"
        )?.run {
            this.addOnSuccessListener {
                printI("save drive file content success  $fileId")
            }
            this.addOnFailureListener {
                printException("save drive file content fair", it)
            }
        }
    }


    /**
     * 切换账号需要，调用释放的函数
     */
    fun release() {
        if (driveServiceHelper != null) {
            driveServiceHelper!!.release();
            driveServiceHelper = null
        }
    }

    interface GoogleApiListener<T> {

        fun success(result: T)

        fun error(e: Exception)
    }
}